package com.everflourish.yeah100.act.markingsystem;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.TopicSettingAdapter;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.entity.marking.TopicModel;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.utils.JsonUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.TopicUtil;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pnikosis.materialishprogress.ProgressWheel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/6/3.
 * 时间：2016/6/3
 */
public class FragmentTopicSetting extends BaseFragment implements View.OnClickListener {

    public MarkingMenuActivity mMarkingMenuActivity;
    public RecyclerView mTopicRecyclerView;
    private LinearLayout mTopicEditLl;
    private ProgressWheel mProgress;
    private FrameLayout mRefreshFl;
    private List<TopicModel> mList;
    public List<Topic> mTopics;
    private TopicSettingAdapter mAdapter;
    private MarkingSystemRequest mRequest;
    private TextView mAddTopicTv, mRefreshTv;
    private boolean isUpload = true;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。
    private Context mContext;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_topic_setting, container,
                false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
        initWidget();
        configWidget();
        isPrepared = false;
    }

    private void initData() {
        mContext = mMarkingMenuActivity = (MarkingMenuActivity) getActivity();
        mRequest = MarkingSystemRequest.getInstance();
        mList = new ArrayList<TopicModel>();
        mAdapter = new TopicSettingAdapter(mContext, mList, this);
    }

    private void initWidget() {
        mTopicRecyclerView = (RecyclerView) getView().findViewById(R.id.item_topic_list);
        mTopicEditLl = (LinearLayout) getView().findViewById(R.id.fragment_topic_edit);
        mAddTopicTv = (TextView) getView().findViewById(R.id.topic_add_tv);
        mAddTopicTv.setOnClickListener(this);
        mProgress = (ProgressWheel) getView().findViewById(R.id.topic_progress);
        mRefreshFl = (FrameLayout) getView().findViewById(R.id.topic_refresh_fl);
        mRefreshTv = (TextView) getView().findViewById(R.id.include_refresh_tv);
        mRefreshTv.setTextColor(mContext.getResources().getColor(R.color.marking_appbar_primaryDark));
        mRefreshTv.setOnClickListener(this);
    }

    private void configWidget() {
        mTopicRecyclerView.setAdapter(mAdapter);
        mTopicRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        mTopicRecyclerView.setItemAnimator(new CustomItemAnimator());
        if (mMarkingMenuActivity.mExamination == null) {
            return;
        }
        getTopicsRequest(mMarkingMenuActivity.mExamination.getId());
    }

    /**
     * 获取题型设置请求
     *
     * @param examinationId
     */
    private void getTopicsRequest(String examinationId) {
        mProgress.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.getTopicsRequest(examinationId,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getTopicsExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mProgress.setVisibility(View.GONE);
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取题型失败");
                        mRefreshFl.setVisibility(View.VISIBLE);
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    private TopicModel mCurrentTopic;

    /**
     * 上传题型信息请求
     *
     * @param topicModel
     */
    public void uploadTopicsRequest(TopicModel topicModel) {
        mProgress.setVisibility(View.VISIBLE);
        mCurrentTopic = topicModel;
        if (!isUpload) {
            mList.remove(topicModel);
        }
        mTopics.clear();
        for (TopicModel t : mList) {
            mTopics.add(t.getTopic());
        }
        JsonObjectRequest request = mRequest.uploadTopicsRequest(
                mMarkingMenuActivity.mExamination.getId(),
                mMarkingMenuActivity.mExamination.getLastModifiedTime(), mTopics,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        uploadTopicsExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mProgress.setVisibility(View.GONE);
                        mRequest.disposeError(mContext, mLoadDialog, error, "上传题型失败");
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 删除题型信息请求
     *
     * @param topicModel
     */
    public void deleteTopicsRequest(TopicModel topicModel) {
        mProgress.setVisibility(View.VISIBLE);
        mList.remove(topicModel);
        mTopics.clear();
        for (TopicModel t : mList) {
            mTopics.add(t.getTopic());
        }
        JsonObjectRequest request = mRequest.uploadTopicsRequest(
                mMarkingMenuActivity.mExamination.getId(),
                mMarkingMenuActivity.mExamination.getLastModifiedTime(), mTopics,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        deleteTopicsExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mProgress.setVisibility(View.GONE);
                        mRequest.disposeError(mContext, mLoadDialog, error, "删除题型失败");
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 获取题型信息监听
     *
     * @param response
     */
    private void getTopicsExaminationListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                mTopics = getTopics(response);
                String lastModifiedTime = JsonUtil.getLastModifiedTime(
                        response, null);
                mMarkingMenuActivity.mExamination
                        .setLastModifiedTime(lastModifiedTime);
                // 获取考试信息成功，设置控件显示
                setListData(mTopics);
                // initAddTopic();
                if (mList.size() == 0) {
                    addTopic();
                }
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07041_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07042_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07043_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070499_999999E);
            } else {
                MyToast.showShort(mContext, "获取题型失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取题型失败");
        } finally {
            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 上传基础题型监听
     *
     * @param response
     */
    private void uploadTopicsExaminationListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                mCurrentTopic.setIsEdit(false);
                mCurrentTopic.setIsAdd(false);
                String lastModifiedTime = JsonUtil.getLastModifiedTime(
                        response, null);
                mMarkingMenuActivity.mExamination
                        .setLastModifiedTime(lastModifiedTime);
                mMarkingMenuActivity.isUpdateExamination = true;
                if (mMarkingMenuActivity.mFragmentStandardAnswer != null) {
                    mMarkingMenuActivity.mFragmentStandardAnswer.refreshData();
                }
                if (mMarkingMenuActivity.mFragmentReadPaper != null) {
                    mMarkingMenuActivity.mFragmentReadPaper.refreshData();
                }
                mAdapter.notifyDataSetChanged();
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07031_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07032_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07033_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                MyToast.showShort(mContext, "当前数据已被更改，请刷新后操作");
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070399_999999E);
            } else {
                MyToast.showShort(mContext, "上传题型失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "上传题型失败");
        } finally {
            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 删除题型监听
     *
     * @param response
     */
    private void deleteTopicsExaminationListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                String lastModifiedTime = JsonUtil.getLastModifiedTime(
                        response, null);
                mMarkingMenuActivity.mExamination
                        .setLastModifiedTime(lastModifiedTime);
                mMarkingMenuActivity.isUpdateExamination = true;
                if (mMarkingMenuActivity.mFragmentStandardAnswer != null) {
                    mMarkingMenuActivity.mFragmentStandardAnswer.refreshData();
                }
                if (mMarkingMenuActivity.mFragmentStandardAnswer != null) {
                    mMarkingMenuActivity.mFragmentReadPaper.refreshData();
                }
                mAdapter.notifyDataSetChanged();
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07031_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07032_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07033_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                MyToast.showShort(mContext, "当前数据已被更改，请刷新后操作");
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070399_999999E);
            } else {
                MyToast.showShort(mContext, "上传题型失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "上传题型失败");
        } finally {
            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 提取题型
     *
     * @param response
     * @return
     * @throws JSONException
     */
    public List<Topic> getTopics(JSONObject response) throws JSONException {
        List<Topic> topics = null;
        if (response == null || response.isNull("topics")) {
            topics = new ArrayList<Topic>();
            return topics;
        }
        JSONArray jsonArray = response.getJSONArray("topics");
        Gson gson = new Gson();
        Type type = new TypeToken<List<Topic>>() {
        }.getType();
        topics = gson.fromJson(jsonArray.toString(), type);
        return topics;
    }

    /**
     * 设置mList 将List<Topoic>转换成ArrayList<Map<String,Object>>()
     *
     * @param topics
     */
    private void setListData(List<Topic> topics) {
        mList.clear();
        for (Topic t : topics) {
            TopicModel topicModel = new TopicModel();
            topicModel.setTopic(t);
            mList.add(topicModel);
        }
        mAdapter.notifyDataSetChanged();
//        topicSort(false);
    }

    /**
     * 根据题型的开始题号排序
     *
     * @param isDesc 是否是降序
     */
    private void topicSort(boolean isDesc) {
//        Collections.sort(mList, new TopicListMapCollections(isDesc));
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topic_add_tv:
                if (mRefreshFl.getVisibility() == View.VISIBLE) {
                    MyToast.showShort(mContext, "请先刷新！");
                    return;
                }
                addTopic();
                break;
            case R.id.include_refresh_tv:
                mRefreshTv.setVisibility(View.GONE);
                if (mMarkingMenuActivity.mExamination == null) {
                } else {
                    getTopicsRequest(mMarkingMenuActivity.mExamination.getId());
                }
                break;
            default:
                break;
        }
    }

    /**
     * 添加题型编辑
     */
    private void addTopic() {
        for (TopicModel model : mList) {
            if (model.isAdd() || model.isEdit()) {
                MyToast.showShort(mContext, "请先完成编辑");
                return;
            }
        }
        TopicModel topicModel = new TopicModel();
        Topic topic = new Topic();
        topic.setTopicBegin(TopicUtil.getCurrentMinNo(mList));
        topic.setTopicEnd(TopicUtil.getCurrentMinNo(mList));
        topic.setTopicType(1);
        topic.setTopicName("");
        topic.setTopicPoint(2.0f);
        topic.setTopicPartPoint(0.0f);
        topicModel.setTopic(topic);
        topicModel.setIsAdd(true);
        topicModel.setIsEdit(false);
        mList.add(topicModel);
        mAdapter.notifyDataSetChanged();
        mTopicRecyclerView.smoothScrollToPosition(mList.size());
    }
}